package org.tarena.dang.service;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.tarena.dang.dao.BookDAO;
import org.tarena.dang.dao.impl.BookDAOImpl;
import org.tarena.dang.entity.CartItem;
import org.tarena.dang.entity.Product;

public class CartServiceImp implements CartService {
	private List<CartItem> buyItems = new ArrayList<CartItem>();
	//private List<CartItem> delItems = new ArrayList<CartItem>();
	@Override
	public boolean buy(int pid) throws SQLException {
		// 根据pid获取商品对象，封装成CartItem对象
		BookDAO dao = new BookDAOImpl();
		CartItem cartItem = new CartItem();
		Product book = dao.findByPid(pid);
		cartItem.setPro(book);
		cartItem.setQty(1);
		buyItems.add(cartItem);
		return true;

	}
	@Override
	public double count() {
		int count = 0 ;
		System.out.println("芝加哥 "+buyItems.size());
		for(CartItem c:buyItems){
			if(c.isBuy()){
				System.out.println(c.getPro().getDangPrice()+"&&&&"+c.getQty());
				count += c.getPro().getDangPrice()*c.getQty();
			}
		}
		return count;
	}
	@Override
	public void del(int pid) {
		System.out.println("删除中--"+pid);
		for(CartItem c:buyItems){
			if(pid==c.getPro().getId()){
				c.setBuy(false);
				System.out.println("已经设置为false");
			}
		}
	}
	@Override
	public List<CartItem> getBuyList() {
		List<CartItem> list = new ArrayList<CartItem>();
		for(CartItem c:buyItems){
			if(c.isBuy()){
				list.add(c);
			}
		}
		return list;
	}
	@Override
	public List<CartItem> getDelList() {
		List<CartItem> delList = new ArrayList<CartItem>();
		for(CartItem c:buyItems){
			if(!c.isBuy()){
				delList.add(c);
			}
		}
		return delList;
	}
	@Override
	public void recovery(int pid) {
		for(CartItem c:buyItems){
			if(pid==c.getPro().getId()){
				c.setBuy(true);
			}
		}
	}
	@Override
	public void update(int pid, int pnum) {
		for(CartItem c:buyItems){
			if(pid==c.getPro().getId()){
				c.setQty(pnum);
			}
		}
	}
	@Override
	public double blance() {
		double blance = 0;
		for(CartItem c:buyItems){
			if(c.isBuy()){
				System.out.println(c.getPro().getDangPrice()+"&&&&"+c.getQty());
				blance += (c.getPro().getFixedPrice()-c.getPro().getDangPrice())*c.getQty();
			}
		}
		return blance;
	}
	public List<CartItem> getBuyItems() {
			return buyItems;
	}
	public void setBuyItems(List<CartItem> buyItems) {
		this.buyItems = buyItems;
	}


	

}
